package com.xyazm.fulfill.event;

import com.xyazm.common.enums.OrderStatusChangeEnum;
import com.xyazm.common.utils.JsonUtil;
import com.xyazm.fulfill.domain.entity.OrderFulfillDO;
import com.xyazm.fulfill.domain.entity.OrderFulfillLogDO;
import com.xyazm.fulfill.domain.event.OrderEvent;
import com.xyazm.fulfill.domain.event.OrderOutStockEvent;
import com.xyazm.fulfill.domain.param.TriggerOrderAfterFulfillEventParam;
import com.xyazm.fulfill.enums.OrderFulfillOperateTypeEnum;
import com.xyazm.fulfill.enums.OrderFulfillStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 订单已出库事件处理器
 * @author xuyou
 * @date 2023年02月13日 21:15
 */
@Slf4j
@Service
public class OrderOutStockEventProcessor extends AbstractAfterFulfillEventProcessor {

    @Override
    protected boolean checkFulfillStatus(OrderFulfillDO orderFulfillDO) {
        // 订单状态不是已履约
        if (!OrderFulfillStatusEnum.FULFILL.getCode().equals(orderFulfillDO.getStatus())) {
            log.info("履约单无法出库！orderId={},当前履约单状态status={}", orderFulfillDO.getOrderId(),orderFulfillDO.getStatus());
            return false;
        }
        return true;
    }

    @Override
    protected void doBizProcess(TriggerOrderAfterFulfillEventParam param, OrderFulfillDO orderFulfillDO) {
        // 将履约单状态改为 履约单出库
        OrderFulfillOperateTypeEnum operateType = OrderFulfillOperateTypeEnum.OUT_STOCK_ORDER;
        updateStatusAndSaveLog(orderFulfillDO, operateType);
    }


    @Override
    protected boolean orderNeedSendMsg(TriggerOrderAfterFulfillEventParam param) {
        // 订单只需要发送一次已出库的消息
        // 预售单在创建履约单的时候可能会发生拆的单情况，即创建多个履约单，
        // 每个履约单进行履约调度的时候都会尝试发送订单履约后的消息，如果两个履约单都属于同一笔订单的话，
        // 那么只有在第一笔履约单进行履约调度单时候，会发送消息
        List<OrderFulfillLogDO> logs = orderFulfillLogDAO.list(param.getOrderId(), OrderFulfillStatusEnum.OUT_STOCK.getCode());
        // 由于doBizProcess()会先执行，所以至少会插入一条日志
        return logs.size() <= 1;
    }

    @Override
    protected String buildMsgBody(TriggerOrderAfterFulfillEventParam param) {
        String orderId = param.getOrderId();
        OrderOutStockEvent orderOutStockEvent = (OrderOutStockEvent) param.getAfterFulfillEvent();
        orderOutStockEvent.setOrderId(orderId);
        // 构建订单已出库消息体
        OrderEvent<OrderOutStockEvent> orderEvent = buildOrderEvent(orderId,OrderStatusChangeEnum.ORDER_OUT_STOCKED,
                orderOutStockEvent);
        return JsonUtil.object2Json(orderEvent);
    }

}
